import axios from "axios";

function exitRouterPage() {
    // let system = this.$store.getters.getUserInfo
    this.$router.push({ path: '/login' })    
}
//定义访问前缀
const uri = 'http://localhost:8088'

export function request(url, params, method, type) {
    const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)'
    });


    return new Promise((resolve, reject) => {
            axios({
                method: method,
                url: uri + url,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    // token: this.$store.getters.getToken
                },
                data: params,
            }).then((res) => {
                loading.close();
                let data = statusHandle(res)
                if (data.status === 0) {
                    resolve(res.data)
                } else {
                    this.$notify.error({
                        title: data.title,
                        message: data.message
                    });

                    if (res.data.status == 1001) {
                        exitRouterPage()
                    }
                    reject(res)
                }
            }).catch((err) => {
                loading.close();
                let title = ""
                let message = ""
                if (err.response != null) {
                    title = "服务端请求错误"
                    message = "服务端请求错误"
                } else {
                    title = "客户端请求错误"
                    message = "客户端请求错误"
                }
                this.$notify.error({
                    title: title,
                    message: message
                });

                reject(err)
            });
        }
    )
}

export function requestFile(url, params, fileName) {
    const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)'
    });

    // let companyInfo = {
    //     orgId: this.$store.getters.getUserInfo.orgId,
    //     orgNum: this.$store.getters.getUserInfo.orgNum,
    //     companyId: this.$store.getters.getUserInfo.companyId
    // }
    // params = {...params, ...companyInfo}

    return new Promise((resolve, reject) => {
            axios.post(this.$uri + url, params, {responseType: 'blob'},
                {
                    headers: {
                        "content-type": "multipart/from-data",
                    }
                }).then((res) => {
                if (res.data.status == 1001) {
                    exitRouterPage()
                }

                this.$message.success(fileName != null ? fileName : res.headers['content-disposition'] + "下载中...");

                // 创建a标签
                const link = document.createElement('a')
                //设置下载类型
                let blob = new Blob([res.data], {})
                //设置a标签样式
                link.style.display = 'none'
                //设置a标签url
                link.href = URL.createObjectURL(blob)

                //设置下载后文件名
                if (fileName != null && fileName != "") {
                    link.download = fileName
                } else {
                    link.download = res.headers['content-disposition']
                }
                //页面添加创建的a标签
                document.body.appendChild(link)
                //点击a标签
                link.click()
                //删除a标签
                document.body.removeChild(link)
                loading.close();
            }).catch(error => {
                this.$message.error('下载失败');
                loading.close();
            })
        }
    )
}

export function requestUploadFile(url, params) {
    const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)'
    });

    let formData = new FormData()
    let files = Array.from(params.file); // files是类数组，需要先转为数组
    files.forEach((file) => {
        formData.append("file", file.raw);
    });
    formData.append("type",params.type);
    // formData.append("orgId",this.$store.getters.getUserInfo.orgId);
    // formData.append("orgNum",this.$store.getters.getUserInfo.orgNum);
    // formData.append("companyId",this.$store.getters.getUserInfo.companyId);


    return new Promise((resolve, reject) => {
            axios.post(this.$uri + url, formData,
                {
                    headers: {
                        "content-type": "multipart/from-data;boundary="+new Date().getTime(),
                        token: this.$store.getters.getToken
                    }
                }).then((res) => {
                if (res.data.status == 1001) {
                    exitRouterPage()
                }
                loading.close();
                resolve(res.data)
            }).catch(error => {
                loading.close();
                reject(error)
            })
        }
    )
}

function statusHandle(res) {
    if (res.data == null || res.data == "") {
        return {title: "返回值错误", message: "无返回值", status: 1}
    }

    if (res.data.status == 401) {
        return {title: "无权限", message: "资源无权访问401", status: 1}
    }

    if (res.data.status == 402) {
        return {title: "无tocken", message: "资源无权访问402", status: 1}
    }

    if (res.data.status == 403) {
        return {title: "服务器拒绝", message: "资源不可用403", status: 1}
    }

    if (res.data.status == 404) {
        return {title: "请求的不存在", message: "请求的不存在404", status: 1}
    }

    if (res.data.status == 200) {
        return {title: "请求成功", message: "请求成功", status: 0}
    }

    if (res.data.status == 1001) {
        return {title: "用户未登入", message: "请重新登入", status: 1001}
    }
}
